<template>
  <div class="source">
    <div class="sku-body">
      <el-row :gutter="20" class="option-row">
        <el-col :span="5">
          <el-select
            :disabled="isPreview"
            placeholder="请选择渠道"
            v-model="taxData.channelCode"
            @change="channelChange"
            size="mini"
          >
            <el-option
              v-for="item in channelDatas"
              :key="item.id"
              :label="item.dicName"
              :value="item.dicCode"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <number-input
            :disabled="isPreview"
            v-model="taxData.price"
            placeholder="税后价格"
          ></number-input>
        </el-col>
        <el-col :span="4">
          <el-input
           type="number"
           v-model="taxData.integralAmount"
           placeholder="积分金额"
           :disabled="$parent.submitDatas.isCreditsExchange==='0' || isPreview"></el-input>
        </el-col>
        <el-col :span="4" class="bulkStyle">
          <el-button :disabled="isPreview" @click="fillBulk" class="dark-btn">确定</el-button>
        </el-col>
      </el-row>
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" border>
        <el-table-column prop="image" :label="$t('productCenter.image')" align="center" min-width="70">
          <template slot-scope="scope">
            <el-image
                v-if="scope.row.skuImageList.length > 0"
                :src="scope.row.skuImageList[0].path || ''"
                style="width: 60px; height: 60px; vertical-align: middle"
                fit="fill"
              >
                <div
                  slot="placeholder"
                  class="image-slot"
                  v-loading="true"
                  element-loading-text="加载中"
                ></div>
              </el-image>
            </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in tableColum" :key="index" :prop="item" :label="item" align="center" min-width="110"></el-table-column>
        <el-table-column :label="$t('productCenter.skuCode')" align="center" min-width="120">
          <template slot-scope="scope">
            <el-input v-model="scope.row.skuCode" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="Ext.No" :label="$t('productCenter.productNo')" align="center" min-width="120">
          <template slot-scope="scope">
            <el-input v-model="scope.row.extNo" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" width="80" type="expand">
          <template slot-scope="scope">
            <sku-channel
              :ref="'skuChannel' + scope.$index"
              :channels="channelList"
              :expandskuData="{datas: scope.row.skuPriceList}"
              :tableIdx="scope.$index"
              @removeSku="removeExpandSku"
              :paymentType="paymentType"
              :disabled="isPreview"
              :isCreditsExchange="$parent.submitDatas.isCreditsExchange"
            ></sku-channel>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="shelves-form">
      <el-row style="margin-top: 10px;">
        <el-col :span="1">
          <el-checkbox :disabled="isPreview" class="able-item" v-model="step4Form.dateAvailableAble"></el-checkbox>
        </el-col>
        <el-col :span="15">
          <el-form
            :model="step4Form"
            :rules="rules"
            label-position="top"
            :disabled="!step4Form.dateAvailableAble"
            ref="availableForm"
          >
            <el-form-item prop="AvailableTime">
              <label class="item-label">{{$t('productCenter.availableTime')}}</label>
              <el-date-picker
                type="daterange"
                :disabled="isPreview"
                value-format="timestamp"
                v-model="step4Form.AvailableTime"
                range-separator="to"
                :start-placeholder="$t('orderCenter.startTime')"
                :end-placeholder="$t('orderCenter.endTime')"
                placeholder="Available Time"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px;">
        <el-col :span="1">
          <el-checkbox :disabled="isPreview" class="able-item" v-model="step4Form.onShelfDateAble"></el-checkbox>
        </el-col>
        <el-col :span="15">
          <el-form
            :model="step4Form"
            :rules="rules"
            label-position="top"
            :disabled="!step4Form.onShelfDateAble"
            ref="onShelfForm"
          >
            <el-form-item prop="onShelfTime">
              <label class="item-label">{{$t('productCenter.onShelfTime')}}</label>
              <el-date-picker
                :disabled="isPreview"
                type="daterange"
                value-format="timestamp"
                v-model="step4Form.onShelfTime"
                :picker-options="pickerOptions"
                range-separator="to"
                :start-placeholder="$t('orderCenter.startTime')"
                :end-placeholder="$t('orderCenter.endTime')"
                placeholder="On-Shelf Time"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <bottom-btn
        :showBack="isPreview?false:true"
        @back="handleBack"
        :nextName="isPreview?'上一步':$t('submit')"
        @cancel="handleCancel"
        @next="submit"
        style="margin-top:20px"
      ></bottom-btn>
    </div>
  </div>
</template>

<script>
import BottomBtn from '../../commons/BottomBtn'
import SkuChannel from './components/SkuChannel'
import NumberInput from '@/components/NumberInput/index'
import { mapGetters } from 'vuex'
import { getDetail } from '@/api/catalog'
import { common } from '@/mixins/common'
import { cloneDeep } from 'lodash'
export default {
  name: 'StepTwo',
  components: {
    SkuChannel,
    BottomBtn,
    NumberInput
  },
  mixins: [common],
  data () {
    // 可用日期的规则函数
    var validateAvailabelDate = (rule, value, callback) => {
      if (this.step4Form.dateAvailableAble) {
        if (!value) {
          callback(new Error(this.$t('productCenter.requireAvaliDate')))
        } else if (
          this.step4Form.AvailableTime[0] === this.step4Form.AvailableTime[1]
        ) {
          callback(new Error(this.$t('productCenter.startgtEndDate')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 上架日期的规则函数
    var validateOnShelf = (rule, value, callback) => {
      if (this.step4Form.onShelfDateAble) {
        if (
          this.step4Form.AvailableTime &&
          this.step4Form.AvailableTime.length
        ) {
          if (!value) {
            callback(new Error(this.$t('productCenter.requireDate')))
          } else if (
            this.step4Form.onShelfTime[0] > this.step4Form.AvailableTime[0]
          ) {
            callback(new Error(this.$t('productCenter.onShelfDateError')))
          } else if (
            this.step4Form.onShelfTime[1] < this.step4Form.AvailableTime[1]
          ) {
            callback(new Error(this.$t('productCenter.offShelfDateError')))
          } else {
            callback()
          }
        }
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '全部时间',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              end.setFullYear(2999, 0, 1)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      taxData: {
        channelCode: '',
        taxExclusivePrice: '',
        taxRate: '',
        price: '',
        integralAmount: ''
      },
      tableData: [],
      tableColum: [],
      orgList: [],
      channelList: [],
      channelDatas: [],
      orgDatas: [],
      choosedOrg: '',
      choosedChannel: '',
      preTaxMsrpVal: '',
      afterTaxMsrpVal: '',
      preTaxPriceVal: '',
      afterTaxPriceVal: '',
      afterTaxPriceMonthVal: '',
      preTaxPriceMonthVal: '',
      stockVal: '',
      step4Form: {
        AvailableTime: '',
        onShelfTime: '',
        allowBuy: false,
        dateAvailableAble: false,
        onShelfDateAble: false
      },
      rules: {
        AvailableTime: [
          {
            required: true,
            validator: validateAvailabelDate,
            trigger: ['blur', 'change']
          }
        ],
        onShelfTime: [
          {
            required: true,
            validator: validateOnShelf,
            trigger: ['blur', 'change']
          }
        ]
      },
      varData: [
        {
          optionName: '',
          optionValue: ''
        }
      ],
      productAttributesForm: {
        fit: '',
        brand: '',
        height: ''
      },
      isEdited: false,
      paymentType: '',
      isPreview: false
    }
  },
  props: ['model'],
  watch: {
    nowDataString: {
      handler (val) {
        if (val) {
          this.isEdited = true
        }
      },
      deep: true
    }
  },
  computed: {
    nowDataString () {
      return (
        JSON.stringify(this.choosedOrg) +
        JSON.stringify(this.preTaxMsrpVal) +
        JSON.stringify(this.afterTaxMsrpVal) +
        JSON.stringify(this.preTaxPriceVal) +
        JSON.stringify(this.afterTaxPriceVal) +
        JSON.stringify(this.stockVal) +
        JSON.stringify(this.step4Form) +
        JSON.stringify(this.preTaxPriceMonthVal) +
        JSON.stringify(this.afterTaxPriceMonthVal) +
        JSON.stringify(this.tableData)
      )
    },
    ...mapGetters(['lookupItems'])
  },
  created () {
    this.channelDatas = this.lookupItems.CHANNEL
  },
  mounted () {
    this.isPreview = this.model.isPreview || false
  },
  methods: {
    getTax (taxData) {
      getDetail(this.$parent.submitDatas.catalogId).then(res => {
        this.$parent.pageLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            taxData.taxRate = res.obj.taxRate
            this.tableData.forEach(item => {
              if (item.skuPriceList && item.skuPriceList.length > 0) {
                item.skuPriceList.forEach(items => {
                  if (items.channelCode === taxData.channelCode) {
                    items.price = taxData.price
                    items.taxRate = taxData.taxRate
                    items.integralAmount = taxData.integralAmount
                    items.taxExclusivePrice = (taxData.price / (1 + taxData.taxRate)).toFixed(2)
                  } else {
                    const lists = cloneDeep(taxData)
                    item.skuPriceList.push(lists)
                  }
                })
              } else {
                taxData.taxExclusivePrice = (taxData.price / (1 + taxData.taxRate)).toFixed(2)
                const lists = cloneDeep(taxData)
                item.skuPriceList.push(lists)
              }
            })
          } else {
            this.$alert(res.code)
          }
          this.$parent.pageLoading = false
        }
      }).catch(() => {
        this.$parent.pageLoading = false
      })
    },
    channelChange () {},
    orgChange (val) {
      const nowOrgObj = this.orgList.find(item => {
        return item.orgId === this.choosedOrg
      })
      const taxRate = (nowOrgObj && nowOrgObj.taxRate) || 0
      if (this.afterTaxMsrpVal) {
        this.preTaxMsrpVal = parseFloat(
          Number(this.afterTaxMsrpVal) / (1 + taxRate)
        ).toFixed(2)
      }
      if (this.afterTaxPriceVal) {
        this.preTaxPriceVal = parseFloat(
          Number(this.afterTaxPriceVal) / (1 + taxRate)
        ).toFixed(2)
      }
      if (this.afterTaxPriceMonthVal) {
        this.preTaxPriceMonthVal = parseFloat(
          Number(this.afterTaxPriceMonthVal) / (1 + taxRate)
        ).toFixed(2)
      }
    },
    // 编辑时初始化数据
    initDatas (initDatas) {
      if (initDatas) {
        this.spuImageList = initDatas.spuImageList
        this.spuId = initDatas.spuId
        this.paymentType = initDatas.paymentType
        // 取出国家数据
        initDatas.responseOrganizationTaxVo &&
          initDatas.responseOrganizationTaxVo.forEach(item => {
            this.orgList.push({
              orgId: item.orgId,
              orgName: item.orgName,
              taxRate: item.taxRate
            })
          })
        const tableColum = []
        const initOptionsDatas = initDatas.spuSkuAttributeList || []
        initOptionsDatas.forEach(item => {
          tableColum.push(item.label)
        })
        this.tableColum = tableColum
        const responseSkuList = initDatas.responseSkuList || []
        const tableDatas = []
        responseSkuList &&
          responseSkuList.forEach(item => {
            item.skuPriceList &&
              item.skuPriceList.forEach(skuData => {
                skuData.preTaxMsrp = skuData.taxExclusiveMsrp
                skuData.afterTaxMsrp = skuData.msrp
                skuData.preTaxPrice = skuData.taxExclusivePrice
                skuData.afterTaxPrice = skuData.price
              })
            const obj = {
              id: item.id,
              skuImageList: item.skuImageList,
              extNo: item.extNo,
              usableStock: item.usableStock,
              isUseRealStock: item.isUseRealStock,
              skuCode: item.skuCode,
              key: item.barcode,
              skuPriceList: item.skuPriceList,
              skuAttributeList: item.skuAttributeList
            }
            item.skuAttributeList.forEach(attr => {
              obj[attr.label] = attr.value
            })
            tableDatas.push(obj)
          })
        // deliveryList
        this.spuDeliveryList = initDatas.responseSpuDeliveryList
        this.tableData = tableDatas
        if (initDatas.shelvesData) {
          this.step4Form = initDatas.shelvesData
          if (!initDatas.shelvesData.AvailableTime[0]) {
            this.step4Form.AvailableTime = null
          }
          if (!initDatas.shelvesData.onShelfTime[0]) {
            this.step4Form.onShelfTime = null
          }
        }
      }
      this.$nextTick(() => {
        this.isEdited = false
      })
    },
    // 取消
    handleCancel () {
      this.$emit('cancel')
    },
    // 返回
    handleBack () {
      this.$emit('back', this.spuId)
      this.orgList = []
    },
    // 表单提交按钮点击
    submit () {
      // 表单判断
      if (this.isPreview) {
        this.$parent.prev(this.spuId)
        return false
      }
      const submitDatas = this.$parent.submitDatas
      let submitFlag = true
      this.step4Form.AvailableTime &&
        this.$refs.availableForm.validate(valid => {
          submitFlag = submitFlag && valid
        })
      this.step4Form.onShelfDateAble &&
        this.$refs.onShelfForm.validate(valid => {
          submitFlag = submitFlag && valid
        })
      if (!submitFlag) {
        return false
      }
      // 表单提交
      const formData = {
        autoOnDate: this.step4Form.onShelfTime
          ? this.step4Form.onShelfTime[0]
          : null,
        autoOffDate: this.step4Form.onShelfTime
          ? this.step4Form.onShelfTime[1]
          : null,
        autoOnOffFlag: this.step4Form.onShelfDateAble ? '1' : '0',
        buyCycleBeginDate: this.step4Form.dateAvailableAble
          ? this.step4Form.AvailableTime[0]
          : null,
        buyCycleEndDate: this.step4Form.dateAvailableAble
          ? this.step4Form.AvailableTime[1]
          : null,
        buyCycleFlag: this.step4Form.dateAvailableAble ? '1' : '0',
        id: this.step4Form.id,
        selloutAutoOffFlag: this.step4Form.allowBuy ? '1' : '0'
      }
      submitDatas.shelvesConfig = formData
      submitDatas.skuList = this.tableData
      submitDatas.skuList.forEach(item => {
        item.skuImage = item.skuImageList[0]
        const skuPriceList = []
        item.skuPriceList.forEach(items => {
          const arr = {}
          arr.id = items.id
          arr.channelCode = items.channelCode
          arr.price = items.price
          arr.integralAmount = items.integralAmount
          arr.taxRate = items.taxRate
          arr.includeTaxPrice = items.includeTaxPrice
          arr.taxExclusivePrice = items.taxExclusivePrice
          arr.enableFlag = items.enableFlag
          skuPriceList.push(arr)
        })
        item.skuPriceList = skuPriceList
      })
      this.$emit('startLoading')
      this.$emit('submit', submitDatas, 'submit')
    },
    // 填充选中组织数据池数据
    fillBulk () {
      const taxData = this.taxData
      if (taxData.channelCode === '') {
        this.$alert('请选择渠道')
        return false
      }
      if (taxData.price === '') {
        this.$alert('请填写税后价格')
        return false
      }
      this.$parent.pageLoading = true
      this.getTax(taxData)
      setTimeout(() => {
        this.$parent.pageLoading = false
        this.taxData = {
          channelCode: '',
          taxExclusivePrice: '',
          taxRate: '',
          price: '',
          integralAmount: ''
        }
        this.$alert('添加成功')
      }, 200)
    },
    // 删除一条channel数据
    removeExpandSku (tableIdx, index) {
      this.tableData[tableIdx].skuPriceList.splice(index, 1)
    },
    // 保存channel
    saveExpandSku (tableIdx) {
      this.$refs.multipleTable.toggleRowExpansion(this.tableData[tableIdx])
      this.expandSkuArr.push(true)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import '@/styles/variables.scss';
.option-row {
  margin-bottom: 20px;
}

.able-item {
  margin-top: 10px;
}

.name-desc {
  margin-left: 10px;
}

.item-label {
  line-height: 40px;
}

h1 {
  position: relative;
  padding-left: 16px;
  line-height: 30px;
  font-size: 14px;
  background-color: #f4f4f4;

  &::before {
    content: "";
    display: block;
    position: absolute;
    left: 0;
    height: 100%;
    width: 4px;
    background-color: #00aca1;
  }
}

/deep/ .el-form-item,
.el-input {
  margin-bottom: 0;
}

.img-box {
  width: 100%;
  position: relative;

  img {
    width: 100%;
  }

  span {
    position: absolute;
    bottom: 0;
    left: 0;
    display: inline-block;
    width: 100%;
    height: 14px;
    font-size: 10px;
    text-align: center;
    line-height: 14px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
  }
}

.img-demo {
  width: 100%;

  img {
    width: 100%;
  }
}
.bulkStyle {
  height: $inputHeight;
  line-height: $inputHeight;
}
/deep/ .el-input__inner {
  height: $inputHeight;
}
.source {
  margin-top: 0px;
}
/deep/ .el-date-editor{
  .el-range-separator{
    line-height: 22px;
  }
  .el-range__icon{
    line-height: 22px;
  }
  .el-range__close-icon{
    line-height: 22px;
  }
}
</style>
